// id, comp, start, limit,name
const edu_safety_point_records = [
  [1, 3001, '2010-6-1', '2033-6-1', '教学楼二层配电箱'],
  [2, 3001, '2018-3-1', '2029-3-1', '操场篮球架'],
  [3, 3001, '2000-9-1', '2023-9-1', '实验室电子仪器'],
  [4, 3001, '2001-8-1', '2031-8-1', '教学楼一层配电箱'],
  [5, 3001, '2019-5-1', '2022-5-1', '教学楼热水器'],
  [6, 3001, '1999-1-1', '2021-1-1', '宿舍楼外瓷砖'],
  [7, 3001, '2015-10-1', '2021-10-1', '厨房中央空调']
]

const edu_safety_point = {
  metadata: {
    name: { type: 'char' },
    company_id: { type: 'many2one', relation: 'res.company' },
    start_date: { type: 'date' },
    limit_date: { type: 'date' },
    days_all: { type: 'integer', compute: '_compute_days' },
    days_used: { type: 'integer', compute: '_compute_days' },
    days_rest: { type: 'integer', compute: '_compute_days' },
    percentage_used: { type: 'integer', compute: '_compute_days' },
    state: { type: 'char', compute: '_compute_days' }
  },

  records: edu_safety_point_records.map(item => {
    const [id, company_id, start_date, limit_date, name] = item
    return { id, company_id, start_date, limit_date, name }
  }),

  extend: BaseModel => {
    //
    class Model extends BaseModel {
      _compute_days(rec) {
        const to_date = str => {
          const newStr = str.replace(/-/g, '/')
          return new Date(newStr)
        }

        const get_days = (date1, date2) => {
          const ms = date2.getTime() - date1.getTime()
          return Math.floor(ms / (24 * 3600 * 1000))
        }

        const start_date = to_date(rec.start_date)
        const limit_date = to_date(rec.limit_date)
        const today = new Date()

        const days_used = get_days(start_date, today)
        const days_all = get_days(start_date, limit_date)
        const days_rest = days_all - days_used

        let percentage = days_all
          ? Math.floor((days_used / days_all) * 100 + 0.5)
          : 0

        if (percentage > 100) {
          percentage = 100
        }

        if (percentage < 0) {
          percentage = 0
        }

        let state
        if (percentage > 80) {
          state = 'exception'
        } else if (percentage > 60) {
          state = 'warning'
        } else if (percentage > 40) {
          state = 'success'
        } else {
          state = undefined
        }

        return {
          days_all,
          days_used,
          days_rest,
          percentage_used: percentage,
          state
        }
      }
    }

    return Model
  }
}

export default {
  'edu.safety.point': edu_safety_point
}
